package com.gem.back.service;

import com.gem.back.entity.AoaRole;
import com.gem.back.entity.AoaUser;
import com.gem.back.mapper.AoaUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.ui.Model;

;import java.util.ArrayList;
import java.util.List;

/**
 * @Description:专门用于security账户验证的服务层
 */
public class CustomUserService implements UserDetailsService {
    @Autowired
    private AoaUserMapper aoaUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AoaUser user = aoaUserMapper.findUserByName(username);
        System.out.println(user);
        if (user != null){
            List<AoaRole> roles = user.getRoles();//获取用户角色
            List<GrantedAuthority> authorities = new ArrayList<>();//保存用户角色
            for (AoaRole role : roles){
                if (role != null && role.getRoleName() != null){
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleName());
                    authorities.add(grantedAuthority);
                }
            }
            return new User(user.getUserName(),user.getPassword(),authorities);
        }else {
            throw new UsernameNotFoundException("admin:" + username + "do not exist!");
        }
    }
}
